BinTree Insert( BinTree BST, ElementType X ){
	if(BST==NULL){
		BST=(BinTree)malloc(sizeof(struct TNode));
		BST->Data=X;
		BST->Left=BST->Right=NULL;
	}
	else if(X<BST->Data) BST->Left=Insert(BST->Left,X);
	else BST->Right=Insert(BST->Right,X);
	return BST;
}
BinTree Delete( BinTree BST, ElementType X ){
	BinTree BT=BST,q;
	q=BT;
	while(1){
		if(BT==NULL) break;
		if(BT->Data==X) break;
		q=BT;
		if(BT->Data>X)  BT=BT->Left;
		else if(BT->Data<X) BT=BT->Right;
	}
	if(BT==NULL){
		printf("Not Found\n");
	}
	else if(BT->Right==NULL&&BT->Left==NULL){
		if(BT==BST) return  NULL;
		if(q->Left==BT){
			q->Left=NULL;
		}
		else q->Right=NULL;
		free(BT);
	}
	else if(BT->Right==NULL&&BT->Left!=NULL&&BT!=BST){
		if(q->Left==BT){
			q->Left=BT->Left;
		}
		else {
			q->Right=BT->Left;
		}
		free(BT);
	}
	else if(BT->Left==NULL&&BT->Right!=NULL&&BT!=BST){
		if(q->Left==BT){
			q->Left=BT->Right;
		}
		else q->Right=BT->Right;
		free(BT);
	}
	else {
		BinTree p=BT,s=BT->Left;
		if(BT==BST&&BT->Left==NULL){
			return BT->Right;
		}
		while(s->Right!=NULL){
			p=s;
			s=s->Right;
		}
		BT->Data=s->Data;
		if(p!=BT){
			p->Right=s->Left;
		}
		else {
			p->Left=s->Left;
		}
		free(s);
	}
	return BST;
}
Position Find( BinTree BST, ElementType X ){
	if(BST==NULL||BST->Data==X) return BST;
	else if(X<BST->Data) return Find(BST->Left,X);
	else return Find(BST->Right,X);	
}
Position FindMin( BinTree BST ){
	if(BST==NULL) return BST;
	while(BST->Left){
		BST=BST->Left;
	}
	return BST;
}
Position FindMax( BinTree BST ){
	if(BST==NULL) return BST;
	while(BST->Right){
		BST=BST->Right;
	}
	return BST;
}
